from django.shortcuts import render,HttpResponse,redirect,reverse
from product.models import *
from cart.models import *

#商品列表
def product_list(request):
    products=Product.objects.all()
    sort_by=request.POST.get('sort_by')
    print(sort_by)
    if sort_by == 'name':
        products=products.order_by('name')
    if sort_by == 'price':
        products=products.order_by('price')
    return render(request,'product_list.html',{'products':products})

#商品详情细节
def product_detail(request,pid):
    product=Product.objects.get(id=pid)
    return render(request,'product_detail.html',{'product':product})

#将商品添加到购物车
def product_add(request,pid):
    num=request.POST.get('num')
    if num == '':
        num=1
    number=Cart()
    number.quantity=num
    number.product_id=pid
    number.save()
    return redirect(reverse('product:product_list'))

# Create your views here.

